<template>
  <div>
    <div class="card" style="margin-bottom: 10px;">
      <el-input v-model="name" prefix-icon="Search" style="width: 300px; margin-right: 10px" placeholder="请输入活动名称查询"></el-input>
      <el-button type="primary" @click="load(1)">查询</el-button>
      <el-button type="info" style="margin: 0 10px" @click="reset">重置</el-button>
    </div>

    <div class="card" style="margin-bottom: 10px">
      <div style="margin-bottom: 10px">
        <el-button type="primary" @click="addCollectionForm">新增</el-button>
        <el-button type="danger" @click="delBatch">批量删除</el-button>
      </div>
      <el-table :data="tableData" style="width: 100%" stripe :header-cell-style="{backgroundColor: 'aliceblue', color: '#666'}" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column prop="name" label="活动名"/>
        <el-table-column prop="picture" label="活动图片">
          <template v-slot="scope">
            <img :src="scope.row.picture || 'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png'" alt="" style="width: 50px; height: 50px; border-radius: 50%">
          </template>
        </el-table-column>
        <el-table-column prop="description" show-overflow-tooltip label="活动简介"/>
        <el-table-column prop="content" label="活动详情">
          <template v-slot="scope">
            <el-button type="primary" @click="showContent(scope.row)">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="活动场地"/>
        <el-table-column prop="time" label="活动时间"/>
        <el-table-column prop="head" label="活动负责人"/>
        <el-table-column prop="price" label="票务价格"/>
        <el-table-column prop="showState" label="上线状态">
          <template v-slot="scope">
            <span v-if="scope.row.showState">上线中</span>
            <span v-else>未上线</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template v-slot="scope">
            <el-button type="primary" @click="updateActivityForm(scope.row)">编辑</el-button>
            <el-button type="danger" @click="deleteActivity(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin: 10px 0">
      <div class="example-pagination-block">
        <el-pagination
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog
        v-model="activityFormVis"
        title="新增活动"
        width="60%"
        @close="closeDialog"
    >
      <el-form :model="activityForm" label-width="100px" style="padding-right: 20px" :rules="rules" ref="activityForm">
        <el-form-item label="活动名" prop="name">
          <el-input v-model="activityForm.name" auto-complete="off" placeholder="请输入活动名"></el-input>
        </el-form-item>
        <el-form-item label="活动图片" prop="avatar">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:9090/file/upload"
              list-type="picture"
              ref="upload"
              :on-success="handlePictureSuccess"
          >
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="活动简介" prop="description">
          <el-input v-model="activityForm.description" type="textarea" auto-complete="off" placeholder="请输入活动简介"></el-input>
        </el-form-item>
        <el-form-item label="活动详情" prop="content">
          <div id="editor"></div>
        </el-form-item>
        <el-form-item label="活动地点" prop="location">
          <el-input v-model="activityForm.location"  auto-complete="off" placeholder="请输入活动地点"></el-input>
        </el-form-item>
        <el-form-item label="活动时间" prop="time">
          <el-input v-model="activityForm.time"  auto-complete="off" placeholder="请输入活动时间"></el-input>
        </el-form-item>
        <el-form-item label="活动负责人" prop="head">
          <el-input v-model="activityForm.head"  auto-complete="off" placeholder="请输入活动负责人"></el-input>
        </el-form-item>
        <el-form-item label="票务价格" prop="price">
          <el-input v-model="activityForm.price"  auto-complete="off" placeholder="请输入活动票务价格"></el-input>
        </el-form-item>
        <el-form-item label="上线状态" prop="showState">
          <el-switch
              v-model="activityForm.showState"
              style="--el-switch-on-color: #32cb21; --el-switch-off-color: #c1c9c5"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" style="text-align: right;">
        <el-button @click="activityFormVis = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
        v-model="activityVisible"
        title="活动说明"
        width="60%"
    >
      <div class="w-e-text">
        <div v-html="content"></div>
        <div slot="footer" style="text-align: right;">
          <el-button @click="activityVisible = false">确 定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import { ElMessage, ElMessageBox } from "element-plus";
import E from "wangeditor";
import hljs from "highlight.js";

export default {
  name: "User",
  data() {
    return {
      activityFormVis: false,
      activityVisible: false,
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      name: '',
      activityForm: {},
      ids: [],
      editor: null,
      content: '',

      rules: {
        description: [
          { required: true, message: '请输入活动简介', trigger: 'blur' },
          { min: 3, max: 40, message: '最多 40 个字', trigger: 'blur' }
        ],
      }
    }
  },
  created() {
    this.load();
  },
  methods: {
    reset() { // 重置查询条件
      this.name = '';
      this.type = '';
      this.load();
    },
    load(pageNum) { // 分页查询
      if (pageNum) {
        this.pageNum = pageNum;
      }
      request.get('/activity/selectByPage', {
        params: { pageNum: this.pageNum, pageSize: this.pageSize, name: this.name }
      }).then(res => {
        if (res && res.data && typeof res.data === 'object') {
          this.tableData = res.data.list || [];
          this.total = res.data.total || 0;
          console.log("活动数据:", this.tableData);
        } else {
          console.error("无效的响应数据:", res);
          ElMessage.error('获取活动数据失败，请稍后再试');
        }
      }).catch(err => {
        console.error("获取活动数据失败:", err);
      });
    },
    handleCurrentChange(pageNum) {
      this.load(pageNum);
    },
    save() {
      this.$refs.activityForm.validate(async valid => {
        if (valid) {
          // 获取编辑框中的数据
          let content = this.editor.txt.html();
          this.activityForm.content = content;
          request({
            url: this.activityForm.id ? '/activity/update' : '/activity/add',
            method: this.activityForm.id ? 'put' : 'post',
            data: this.activityForm,
          }).then(response => {
            if (response.code === 1) {
              ElMessage.success('保存成功');
              this.activityFormVis = false;
              this.load();
            } else {
              ElMessage.error(response.msg);
            }
          });
        }
      });
    },
    deleteActivity(row) {
      console.log("删除活动:", row.id);
      ElMessageBox.confirm(
          `是否确定删除活动 ${row.name}?`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(() => {
        request.delete(`/activity/delete/${row.id}`).then(response => {
          if (response.code === 1) {
            ElMessage.success('删除成功');
            this.load();
          } else {
            ElMessage.error(response.msg);
          }
        });
      }).catch(() => {});
    },
    updateActivityForm(row) { // 编辑数据表单
      this.activityForm = JSON.parse(JSON.stringify(row)); // 给form对象赋值 深拷贝
      this.activityFormVis = true; // 显示表单
      this.setRichText()
      setTimeout(() => {  // 延迟执行，等到编辑器加载完成，再设置内容
        this.editor.txt.html(row.content);  // 设置编辑器内容
      })
    },
    addCollectionForm() { // 新增数据表单
      this.activityForm = {};
      this.activityFormVis = true; // 显示表单
      this.setRichText()
    },
    handlePictureSuccess(response, file, fileList) {
      this.activityForm.picture = response.data;
    },
    handleSelectionChange(rows) {
      this.ids = rows.map(item => item.id);
    },
    delBatch() {
      if (this.ids.length === 0) {
        ElMessage.error('请选择要删除的活动');
        return;
      }
      ElMessageBox.confirm(
          `是否确定删除选中的 ${this.ids.length} 个活动?`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(() => {
        request.delete(`/activity/delete/batch`, { data: this.ids }).then(response => {
          if (response.code === 1) {
            ElMessage.success('删除成功');
            this.load();
          } else {
            ElMessage.error(response.msg);
          }
        });
      });
    },
    closeDialog() {
      if (this.editor) {
        this.editor.destroy();  // 销毁编辑器
        this.editor = null;
      }
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles(); // 清除上传文件
      }
    },
    showContent(row) {
      this.activityVisible = true;
      this.content = row.content;
    },
    setRichText(){  // 富文本框设置
      this.$nextTick(() => {
        if (!this.editor) {
          this.editor = new E('#editor');
          this.editor.highlight = hljs;  // 代码高亮

          //富文本框上传图片
          this.editor.config.uploadImgServer = 'http://localhost:9090/file/editor/upload';
          this.editor.config.uploadFileName = 'file';
          this.editor.config.uploadImgHeaders = {
            token: localStorage.getItem('token')
          };
          this.editor.config.uploadImgParams = {
            type: 'img'
          };
          // 上传视频
          this.editor.config.uploadVideoServer = 'http://localhost:9090/file/editor/upload';
          this.editor.config.uploadVideoName = 'file';
          this.editor.config.uploadVideoHeaders = {
            token: localStorage.getItem('token')
          };
          this.editor.config.uploadVideoParams = {
            type: 'video'
          };
          this.editor.create();  // 创建编辑器
        }
      })
    }
  }
}
</script>

<style scoped>
.example-pagination-block + .example-pagination-block {
  margin-top: 10px;
}
</style>
